package com.svo.weitu;

import java.util.List;
import java.util.Vector;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.svo.weitu.activity.MainActivity;
import com.svo.weitu.model.db.ResData;
import com.svo.weitu.model.entity.MenuEntity;
import com.svo.weitu.model.push.MPush;

public class OrderAdapter extends BaseAdapter {
	private List<MenuEntity> entities;
	private Context context;
	Vector<Integer> ids;
	public OrderAdapter(Context context, List<MenuEntity> entities, Vector<Integer> ids) {
		this.context = context;
		this.entities = entities;
		this.ids = ids;
	}

	@Override
	public int getCount() {
		return entities.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = LayoutInflater.from(context).inflate(R.layout.order_item, null);
		final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.item_cb);
		TextView title = (TextView) convertView.findViewById(R.id.item_tv);
		final MenuEntity entity = entities.get(position);
		title.setText(entity.getTitle());
		if (ids.contains(entity.getId())) {
			checkBox.setChecked(true);
		} else {
			checkBox.setChecked(false);
		}
		convertView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				MainActivity.isRefresh = true;
				if (checkBox.isChecked()) { // 去取消
					new ResData(context).subDelete(entity.getId());
					new MPush(context).delTag(entity.getId() + "");
				} else { // 去订阅
					new ResData(context).subRes(entity.getId());
					new MPush(context).addTag(entity.getId() + "");
				}
				checkBox.setChecked(!checkBox.isChecked());
				((MainActivity)context).refresh();
			}
		});
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				MainActivity.isRefresh = true;
				if (!isChecked) { // 去取消
					new ResData(context).subDelete(entity.getId());
					new MPush(context).delTag(entity.getId() + "");
				} else { // 去订阅
					new ResData(context).subRes(entity.getId());
					new MPush(context).addTag(entity.getId() + "");
				}
				((MainActivity)context).refresh();
			}
		});
		return convertView;
	}
}
